Proposed Exercise: Function rect()
Proposed Exercise: Creating the function rect()
One example of an application that uses Lua to expose scripting power to users is PICO-8.
PICO-8 is what we call a fantasy console, meaning it is an application that emulates a console that never existed in real life. Besides being this console emulator, PICO-8 could also be considered a very small game engine, where the user has access to a code editor, a sprite/pixel editor, music editor, and other small little creation tools to create their own games inside the fantasy console.
When you start PICO-8 you are welcomed with a terminal window:
The terminal allows you to list the files (ls), change directories (cd), clear the screen (cls), run games (run), and many other useful commands. As you can see, not only PICO-8 emulates a gaming console but tries to emulate a simple OS terminal with files and folders.
Besides being able to load and run games, PICO-8 has a small code editor, where the user can write simple programs using the language Lua. Here is an example of a program written inside PICO-8:
As you can see, PICO-8 has a built-in function called _update() and another function called _draw(). These functions run 30 frames per second, update is called first, and draw later.
Do you see how PICO-8 uses Lua, but also expanded the pure Lua language to allow some different operators to be used by the user?
- Can you quickly go to the discussion forum and write down what is something different that you could spot in the PICO-8 code that we could not do in pure Lua?
This is a screenshot of our Lua code running inside the PICO-8 engine:
Do you agree that in the last lecture we learned to implement these two functions update and draw binding them to our native C update() and draw() functions? So, in a way, we know now how PICO-8 implements them. Of course, I’m simplifying what update and draw actually do in PICO-8 and some of PICO-8’s internal complexities, but I think we can at least have a good idea of how these two things work under the hood. Another interesting aspect is that the creator of PICO-8, Joseph White, confirmed that he used SDL to develop the console.
PICO-8 also exposes different useful functions. For example, cls() clears the entire screen and rect(x1,y1,x2,x2) draws a rectangle in the screen from top-left position (x1,y1) until bottom-right position (x2,y2).
As an exercise, try implementing this function rect(x1,y1,x2,y2) in our code. The final goal is to allow our Lua script to call rect() and then handle the rendering of the rectangle with C and SDL.
Warning: you can definitely use the SDL function SDL_RenderDrawRect() to draw an SDL_Rect on the screen, but remember that SDLRect is composed of parameters x, y, width, and height, while PICO-8’s rect function works with parameters x1, y1, x2, and y2. You might need to account for that difference.


